<template>
  <Form ref="formCom" :validation-schema="myschema" autocomplete="off" v-slot="{errors}" class="bottom">
              <div class="shang">
                  <img :src="avatar" alt="">
                  <span>Hi，<i>{{nickname}}</i> 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</span>
              </div>
              <div class="mobile">
                  <i class="icon iconfont icon-phone"></i>
                  <Field v-model="form.mobile" name="mobile" class=" input" :class="{active:errors.mobile}" type="text" placeholder="绑定的手机号" />
                  <span v-if="errors.mobile">{{errors.mobile}}</span>
              </div>
              <div class="mobile">
                  <i class="icon iconfont icon-code"></i>
                  <Field name="code" v-model="form.code" type="text" class="input" :class="{active:errors.code}" placeholder="短信验证码" />
                  <span v-if="errors.code">{{errors.code}}</span>
                  <em @click="send">{{time <= 0 ?  '发送验证码':`${time}秒后发送`}}</em>
              </div>
              <a @click="submit" href="javascript:;">立即绑定</a>
  </Form>
</template>

<script>
import QC from 'qc'
import { reactive, ref, onUnmounted } from 'vue'
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import { useIntervalFn } from '@vueuse/core'
import Message from '@/components/libaray/Message'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackBind',
  components: {
    Form,
    Field
  },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    //   1.准备 unionId(openId)  qq头像 昵称
    // 2. 完成表单校验
    // 3.发送验证码(校验，定义APi,调用倒计时)
    // 4.进行绑定(绑定成功就是登陆成功)
    const nickname = ref(null)
    const avatar = ref(null)
    if (QC.Login.check()) {
      QC.api('get_user_info').success(res => {
        console.log(res)
        nickname.value = res.data.nickname
        avatar.value = res.data.figureurl_1
      })
    }
    // 校验规则对象
    const myschema = {
      mobile: schema.mobile,
      code: schema.code
    }
    // 表单数据对象
    const form = reactive({
      mobile: null,
      code: null
    })

    // 发送短信验证码
    // pause暂停，resume开始
    const formCom = ref(null)

    const time = ref(0)
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, { immediate: false })
    // 发送短信
    onUnmounted(() => {
      pause()
    })
    const send = async () => {
      const valid = myschema.mobile(form.mobile)
      if (valid === true) {
        // 通过
        // 没有倒计时才可以发送请求
        if (time.value === 0) {
          try {
            await userQQBindCode(form.mobile)
            Message({ type: 'success', message: '发送成功' })
            time.value = 60
            resume()
          } catch (err) {
            Message({ type: 'error', message: '用户不存在' })
          }
        }
      } else {
        // 失败,使用vee的错误函数显示错误信息 setFieldError(字段名称,错误信息)
        formCom.value.setFieldError('mobile', valid)
      }
    }

    // 立即绑定
    const store = useStore()
    const router = useRouter()
    const submit = async () => {
      const valid = formCom.value.validate()
      if (valid) {
        userQQBindLogin(props.unionId, form.mobile, form.code).then(data => {
        // 绑定成功
        // 实现和之前登录一样的逻辑
          const { id, account, avatar, mobile, nickname, token } = data.result
          store.commit('user/setUser', { id, account, avatar, mobile, nickname, token })

          store.dispatch('cart/mergeCart').then(() => {
            router.push(store.state.user.redirectUrl)
            Message({ type: 'success', message: 'QQ绑定成功' })
          })
        }).catch(error => {
          console.log(error)

          Message({ type: 'error', message: '绑定失败' })
        })
      }
    }

    return { submit, nickname, avatar, Form, Field, form, myschema, send, time, formCom }
  }
}
</script>

<style scoped lang="less">
.bottom {
        padding-top: 30px;
        a {
            display: block;
            width: 320px;
            height: 50px;
            background-color: @xtxColor;
            line-height: 50px;
            text-align: center;
            color: #fff;
            border-radius: 4px;
        }
        .shang {
            img {
                width: 50px;
                height: 50px;
            }
            display: flex;
            align-items: center;
            width: 320px;
            height: 70px;
            background: #f2f2f2;
            padding: 8px 8px;
            span {
                padding-left: 10px;
            }
        }
        .mobile {
            width: 320px;
            height: 50px;
            position: relative;
            margin: 30px 0;
            .input {
                width: 100%;
                height: 100%;
                border: 1px solid #ccc;
                padding-left: 35px;
                &.active {
                    border-color: red;
                }
                &:focus {
                    border-color: @xtxColor;
                }
            }
            i {
                position: absolute;
                top: 14px;
                left: 10px;
                font-size: 16px;
                color: #999;
            }
            span {
                position: absolute;
                left: 330px;
                width: 180px;
                top:15px;
                color: red;
            }
            em {
                position: absolute;
                font-style: normal;
                top: 15px;
                right: 10px;
                color: #999;
                cursor: pointer;
            }
        }
    }
</style>
